//
//  SetView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/26.
//

import SwiftUI
import Kingfisher
import PhotosUI

struct UserInfoView: View {
    @EnvironmentObject var pathManager: PathManager
    @EnvironmentObject var themeManager: ThemeManager
    @EnvironmentObject var userManager: UserManager
    @StateObject var viewModel = UserViewModel()
    @State var showNameAlert = false
    @State var nickName = ""
    @State var showSexPicker = false
    @State var selectSexId = "0"
    @State private var genderOptions = [PickItem(id: "0", name: "男"), PickItem(id: "1", name: "女")]
    @State private var selectedItem: PhotosPickerItem?
    @State private var selectedImage: UIImage?
    @State private var showUploadImage = false
    @State var showQuitLogin = false
    @State var showUnbingWx = false
    @State var showUnbingQQ = false
    @State var showUnbingApple = false
    @State var showDelAccount = false

    
    var body: some View {
        ZStack{
            ScrollView(.vertical) {
                PhotosPicker(selection: $selectedItem, matching: .images) {
                    UserInfoAvatarView(image: $selectedImage)
                } .onChange(of: selectedItem) { newItem in
                    guard let newItem = newItem else {return}
                    Task{
                        if let data = try? await newItem.loadTransferable(type: Data.self) {
                            selectedImage = UIImage(data: data)
                            await MainActor.run {
                                if let uiImage = selectedImage {
                                    viewModel.upload(image: uiImage)
                                }
                            }
                        }
                    }
                }.alert("上传头像",isPresented: $showUploadImage) {
                    Button("取消",role: .cancel) {}
                    Button("上传",role: .destructive) {
                        
                    }
                } message: {
                    Text("是否确定上传该图片")
                }
                
                VStack{
                    HStack{
                        Text("昵称")
                            .font(.system(size: 16))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(.bgNormalText2)
                        Spacer()
                        Text(userManager.getName())
                            .font(.system(size: 14))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(.bgNormalText4)
                        Image(.appIconArrowRight)
                            .resizable()
                            .frame(width: 15,height: 15)
                    }.frame(height: 40)
                        .contentShape(Rectangle())
                        .onTapGesture{
                            showNameAlert.toggle()
                        }
                    HStack{
                        Text("性别")
                            .font(.system(size: 16))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(.bgNormalText2)
                        Spacer()
                        Text(userManager.getSexStr())
                            .font(.system(size: 14))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(.bgNormalText4)
                        Image(.appIconArrowRight)
                            .resizable()
                            .frame(width: 15,height: 15)
                    }.frame(height: 40)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            SwiftEntryKitWrapper.showBottomPopup { dismiss in
                                PickerView(title:"请选择性别",options:genderOptions,selectId:$selectSexId) {
                                    let id = Int(selectSexId) ?? 0
                                    userManager.user?.sex = id
                                    userManager.update()
                                    userManager.request()
                                    dismiss()
                                }
                            }
                        }
                    if !isExamine() {
                        HStack{
                            Text("微信")
                                .font(.system(size: 16))
                                .multilineTextAlignment(.leading)
                                .lineLimit(1)
                                .foregroundStyle(.bgNormalText2)
                            Spacer()
                            let bind = userManager.user?.wx ?? ""
                            Text(!bind.isEmpty ? "已绑定" : "未绑定")
                                .font(.system(size: 14))
                                .multilineTextAlignment(.leading)
                                .lineLimit(1)
                                .foregroundStyle(!bind.isEmpty ? themeManager.themeColor : .bgNormalText4)
                            Image(.appIconArrowRight)
                                .resizable()
                                .frame(width: 15,height: 15)
                        }.frame(height: 40)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                if !(userManager.user?.wx ?? "").isEmpty {
                                    showUnbingWx = true
                                } else {
                                    getLogin(type: LoginType.WX)?.bind()
                                }
                            }
                        HStack{
                            Text("QQ")
                                .font(.system(size: 16))
                                .multilineTextAlignment(.leading)
                                .lineLimit(1)
                                .foregroundStyle(.bgNormalText2)
                            Spacer()
                            let bind = userManager.user?.qq ?? ""
                            Text(!bind.isEmpty ? "已绑定" : "未绑定")
                                .font(.system(size: 14))
                                .multilineTextAlignment(.leading)
                                .lineLimit(1)
                                .foregroundStyle(!bind.isEmpty ? themeManager.themeColor : .bgNormalText4)
                            Image(.appIconArrowRight)
                                .resizable()
                                .frame(width: 15,height: 15)
                        }.frame(height: 40)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                if !(userManager.user?.qq ?? "").isEmpty {
                                    showUnbingQQ = true
                                } else {
                                    getLogin(type: LoginType.QQ)?.bind()
                                }
                            }
                    }
                    HStack{
                        Text("Apple")
                            .font(.system(size: 16))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(.bgNormalText2)
                        Spacer()
                        let bind = userManager.user?.apple ?? ""
                        Text(!bind.isEmpty ? "已绑定" : "未绑定")
                            .font(.system(size: 14))
                            .multilineTextAlignment(.leading)
                            .lineLimit(1)
                            .foregroundStyle(!bind.isEmpty ? themeManager.themeColor : .bgNormalText4)
                        Image(.appIconArrowRight)
                            .resizable()
                            .frame(width: 15,height: 15)
                    }.frame(height: 40)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            if !(userManager.user?.apple ?? "").isEmpty {
                                showUnbingApple = true
                            } else {
                                getLogin(type: LoginType.APPLE)?.bind()
                            }
                        }
                }.padding().background(.bgItem).cornerRadius(15).contentShape(Rectangle())
                Spacer(minLength: 30)
                if userManager.isLogin() {
                    Button(action: {
                        showQuitLogin.toggle()
                    }) {
                        Text("退出登陆")
                            .font(.system(size: 16))
                            .foregroundStyle(themeManager.themeColor)
                    }
                }
            }.navigationTitle("个人信息")
                .padding().background(.bg)
                .toolbar {
                    // 添加一个右标题按钮
                    ToolbarItem(placement: .navigationBarTrailing) {
                        HStack{
                            Text("删除账户")
                                .foregroundColor(themeManager.themeColor)
                                .font(.system(size: 12))
                                .padding(.horizontal,10)
                                .padding(.vertical,7)
                                .cornerRadius(8)
                                .contentShape(Rectangle())
                                .onTapGesture {
                                    showDelAccount.toggle()
                                }
                        }
                    }
                }
                .alert("修改昵称", isPresented: $showNameAlert) {
                    TextField("请输入昵称", text: $nickName)
                        .padding()
                        .border(Color.gray, width: 1)
                    Button("取消",role: .cancel){}
                    Button("确定",role: .destructive) {
                        userManager.user?.name = nickName
                        userManager.update()
                        userManager.request()
                    }
                }
                .alert("温馨提示", isPresented: $showQuitLogin){
                    Button("取消",role: .cancel){}
                    Button("确定",role: .destructive) {
                        userManager.doLogOut()
                        pathManager.back()
                    }
                } message: {
                    Text("是否退出登陆")
                }
                .alert("温馨提示", isPresented: $showUnbingWx){
                    Button("取消",role: .cancel){}
                    Button("确定",role: .destructive) {
                        viewModel.unBind(type: LoginType.WX.rawValue)
                    }
                } message: {
                    Text("是否确定解绑")
                }
                .alert("温馨提示", isPresented: $showUnbingQQ){
                    Button("取消",role: .cancel){}
                    Button("确定",role: .destructive) {
                        viewModel.unBind(type: LoginType.QQ.rawValue)
                    }
                } message: {
                    Text("是否确定解绑")
                }
                .alert("温馨提示", isPresented: $showUnbingApple){
                    Button("取消",role: .cancel){}
                    Button("确定",role: .destructive) {
                        viewModel.unBind(type: LoginType.APPLE.rawValue)
                    }
                } message: {
                    Text("是否确定解绑")
                }
                .alert("温馨提示",isPresented: $showDelAccount) {
                    Button("取消",role: .cancel){}
                    Button("确定删除",role: .destructive) {
                        viewModel.deleteAccount()
                    }
                } message: {
                    Text("您确定是否要删除账户，删除后将无法恢复")
                }
        }
    }
}

/**
 *  用户信息头像
 */
struct UserInfoAvatarView: View {
    @Binding var image: UIImage?
    
    var body: some View {
        HStack() {
            if let image = image {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFill()
                    .clipShape(Circle())
                    .frame(width: 50,height: 50)
            } else {
                KFImage(URL(string: userManager.getAvatar()))
                    .resizable()
                    .placeholder{
                        Image(.appIconLogo)
                            .resizable()
                            .scaledToFill()
                            .clipShape(Circle())
                    }
                    .scaledToFill()
                    .clipShape(Circle())
                    .frame(width: 50,height: 50)
            }
            Text("头像")
                .font(.system(size: 16))
                .multilineTextAlignment(.leading)
                .lineLimit(1)
                .foregroundStyle(.bgNormalText2)
            Spacer()
            Image(.appIconArrowRight)
                .resizable()
                .frame(width: 15,height: 15)
        }.padding().background(.bgItem).cornerRadius(15).contentShape(Rectangle())
    }
}

//#Preview {
//    SetView()
//}


//定义预览提供者
struct UserInfo_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: UserInfoView())
    }
}
